//
//  CategoryViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/14.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class CategoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var _currentTab = 0
    
    var seletedTabIndex:Int{
        get{
            return _currentTab
        }
        set(c){
            _currentTab = c
            
            
            tabbarTableView.reloadData()
            
            var shouldShowWidth:CGFloat = 0.0
            if tabItems != nil {
                for i in 0..<c {
                    let catInfo = tabItems?.object(at: i) as? NSDictionary
                    
                    let catName = catInfo?.object(forKey: "name") as? String
                    
                    if catName != nil{
                        shouldShowWidth += (catName! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
                    }
                    
                }
                if tabbarTableView.contentOffset.y > shouldShowWidth{
                    tabbarTableView.setContentOffset(CGPoint(x: 0, y: shouldShowWidth), animated: true)
                }else if tabbarTableView.contentOffset.y < shouldShowWidth - view.bounds.width {
                    tabbarTableView.setContentOffset(CGPoint(x: 0, y: shouldShowWidth), animated: true)
                }
                
            }
            
            
        }
    }
    
//    convenience init(tab: Int, tabItems: [String]?){
//        self.init()
//        self.tabItems = tabItems as NSArray?
//        _currentTab = tab
//    }
    
    convenience init(tab: Int, tabItems: NSArray?){
        self.init()
        self.tabItems = tabItems
        _currentTab = tab
    }
    
    var tabItems: NSArray?
    
    var tabbarTableView: UITableView!
    var tabScrollView: UIScrollView!
    
    var tableViewInTab: [UITableView]!
    var catDatas: [NSArray] = []
    
    var originShadowImage: UIImage?
    var originNavBarBGImage: UIImage?
//    var originNavDelegate: UIGestureRecognizerDelegate?
    
    var refreshControllers: [UDRefreshControl] = []
    var pageRefreshes: [UDRefreshControl] = []
    
    var currentPages: [Int] = []
    
    var catWidth:CGFloat = 44.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.groupTableViewBackground
        
        navigationController?.navigationBar.isTranslucent = false
        
        catWidth = tabItems != nil ? tabItems!.count != 0 ? view.frame.width/CGFloat(tabItems!.count) : 44 : 44
        
        originShadowImage = navigationController?.navigationBar.shadowImage
        originNavBarBGImage = navigationController?.navigationBar.backgroundImage(for: .default)
//        originNavDelegate = navigationController?.interactivePopGestureRecognizer?.delegate
        
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
//        navigationController?.interactivePopGestureRecognizer?.delegate = self
        
        let tabbarBlurView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 36))
//        tabbarBlurView.effect = UIBlurEffect(style: .dark)
        tabbarBlurView.backgroundColor = themeColor2
        view.addSubview(tabbarBlurView)
        
        tabbarTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 36, height: view.bounds.width))
        tabbarTableView.backgroundColor = UIColor.clear
        tabbarTableView.tag = 438
        tabbarTableView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI/2))
        tabbarTableView.center = CGPoint(x: view.center.x, y: 18)
        
        tabbarTableView.separatorStyle = .none
        tabbarTableView.showsVerticalScrollIndicator = false
        
        tabbarTableView.delegate = self
        tabbarTableView.dataSource = self
        tabbarBlurView.addSubview(tabbarTableView)
        
        tabScrollView = UIScrollView(frame: CGRect(x: 0, y: 36, width: view.frame.width, height: view.frame.height - 36 - 64))
        tabScrollView.tag = 2358
        tabScrollView.delegate = self
        tabScrollView.alwaysBounceHorizontal = true
        tabScrollView.isPagingEnabled = true
        view.addSubview(tabScrollView)
        
        tableViewInTab = []
        if tabItems != nil {
            tabScrollView.contentSize = CGSize(width: tabScrollView.frame.width * CGFloat(tabItems!.count), height: tabScrollView.frame.height)
            let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: tabScrollView.frame.width * CGFloat(tabItems!.count), height: tabScrollView.frame.height))
            stackView.axis = .horizontal
            stackView.distribution = .fillEqually
            for i in 0..<tabItems!.count{
                
                let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: tabScrollView.frame.width, height: tabScrollView.frame.height), style: .plain)
                tableView.tableFooterView = UIView(frame: CGRect.zero)
                tableView.tag = 700 + i
                tableView.delegate = self
                tableView.dataSource = self
                
//                let aView = UILabel(frame: CGRect(x: 16, y: 100, width: tabScrollView.frame.width - 32, height: 20))
//                aView.textAlignment = .center
//                aView.text = "\(i)"
//                tableView.addSubview(aView)
                
                stackView.addArrangedSubview(tableView)
                tableViewInTab.append(tableView)
                
                catDatas.append(NSArray())
                
                let rc = UDRefreshControl(frame: CGRect(x: 0, y: -64, width: view.frame.width, height: 64))
                tableView.addSubview(rc)
                refreshControllers.append(rc)
                
                let pr = UDRefreshControl(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 64))
                pr.normalTitle = "加载更多"
                pageRefreshes.append(pr)
                
                currentPages.append(1)
                
                tableView.tableFooterView = pr
            }
            tabScrollView.addSubview(stackView)
        }
        
        seletedTabIndex = _currentTab
        tabScrollView.setContentOffset(CGPoint(x: tabScrollView.frame.width * CGFloat(_currentTab), y: 0), animated: true)
        refreshList(seletedTabIndex)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.navigationBar.isTranslucent = false
        
//        [self.navigationController.navigationBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
//        [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
//        [self.navigationController.navigationBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
//        
//        [self.tabBarController.tabBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
//        [self.tabBarController.tabBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];

        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.shadowImage = originShadowImage
        navigationController?.navigationBar.setBackgroundImage(originNavBarBGImage, for: .default)
//        navigationController?.interactivePopGestureRecognizer?.delegate = originNavDelegate
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        switch scrollView.tag {
        case tabScrollView.tag:
            seletedTabIndex = Int((scrollView.contentOffset.x + tabScrollView.frame.width/2) / tabScrollView.frame.width)
            
            break
        default:
            if scrollView.tag / 100 == 7 {
                let tabTag = scrollView.tag - 700
                
                if scrollView.contentOffset.y <= -64{
                    if refreshControllers[tabTag].state == .normal{
                        refreshControllers[tabTag].readyToRefresh()
                    }
                    
                }else{
                    if refreshControllers[tabTag].state == .ready{
                        refreshControllers[tabTag].endRefresh()
                    }
                    
                }
//                print("\(scrollView.contentOffset.y) : \(CGFloat(catDatas[tabTag].count+1)*88 - tableViewInTab[tabTag].frame.height)")
                let height = tableViewInTab[tabTag].contentSize.height - tableViewInTab[tabTag].frame.height + 32
                if scrollView.contentOffset.y >= height {
                    if pageRefreshes[tabTag].state == .normal{
                        pageRefreshes[tabTag].readyToRefresh()
                    }
                }else{
                    if pageRefreshes[tabTag].state == .ready{
                        pageRefreshes[tabTag].endRefresh()
                    }
                }
                
            }
            break
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView.tag / 100 == 7 {
            let tabTag = scrollView.tag - 700
            
            if refreshControllers[tabTag].state == .ready {
                refreshList(tabTag)
            }
            
            if pageRefreshes[tabTag].state == .ready{
                getPageList(tabTag)
            }
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        switch scrollView.tag {
        case tabScrollView.tag:
//            print(seletedTabIndex)
            if catDatas[seletedTabIndex].count == 0{
                refreshList(seletedTabIndex)
            }
            
            break
        default:
            break
        }
    }
    
    func refreshList(_ catPage: Int) {
        //http://114.215.105.95/index.php?c=cat&id=3&type=m
        
        refreshControllers[catPage].beginRefresh()
        
        var insert = tableViewInTab[catPage].contentInset
        insert.top += 64
        tableViewInTab[catPage].contentInset = insert
        
        let catInfo = tabItems?.object(at: catPage) as? NSDictionary
        var catID = catInfo?.object(forKey: "id") as? String
        if catID == nil {
            let catInt = catInfo?.object(forKey: "id") as? Int
            if catInt != nil{
                catID = String(catInt!)
            }
        }
        
        if catID != nil{
            let url = URL(string: "\(baseDomainName)/cms/index.php?c=cat&id=\(catID!)&type=m")!
            URLSession.shared.dataTask(with: url, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                DispatchQueue.main.async {
                    self.refreshControllers[catPage].endRefresh()
                    
                    var insert = self.tableViewInTab[catPage].contentInset
                    insert.top -= 64
                    UIView.animate(withDuration: 0.3, animations: { 
                        self.tableViewInTab[catPage].contentInset = insert
                    })
                    
                }
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    let listNews = jsonData?.object(forKey: "listNews") as? NSArray
                    if listNews != nil{
                        self.catDatas[catPage] = listNews!
                    }
                    
                    DispatchQueue.main.async {
                        self.tableViewInTab[catPage].reloadData()
                    }
                    
                }catch let ex{
                    
                    print(ex)
                }
            }).resume()
        }
        
    }
    
    func getPageList(_ catPage: Int){
        pageRefreshes[catPage].beginRefresh()
        
//        var insert = tableViewInTab[catPage].contentInset
//        insert.bottom += 64
//        tableViewInTab[catPage].contentInset = insert
        
        let catInfo = tabItems?.object(at: catPage) as? NSDictionary
        var catID = catInfo?.object(forKey: "id") as? String
        if catID == nil {
            let catInt = catInfo?.object(forKey: "id") as? Int
            if catInt != nil{
                catID = String(catInt!)
            }
        }
        
        let p = currentPages[catPage] + 1
        
        if catID != nil{
            let url = URL(string: "\(baseDomainName)/cms/index.php?c=cat&id=\(catID!)&type=m&page=\(p)")!
            URLSession.shared.dataTask(with: url, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                DispatchQueue.main.async {
                    self.pageRefreshes[catPage].endRefresh()
                    
//                    var insert = self.tableViewInTab[catPage].contentInset
//                    insert.bottom -= 64
//                    UIView.animate(withDuration: 0.3, animations: {
//                        self.tableViewInTab[catPage].contentInset = insert
//                    })
                    
                }
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    let listNews = jsonData?.object(forKey: "listNews") as? NSArray
                    if listNews != nil{
                        
                        self.catDatas[catPage] = self.catDatas[catPage].addingObjects(from: listNews as! [Any]) as NSArray
                        self.currentPages[catPage] += 1
                    }
                    
                    DispatchQueue.main.async {
                        self.tableViewInTab[catPage].reloadData()
                        if listNews == nil{
                            self.pageRefreshes[catPage].normalTitle = "没有更多了"
                        }else{
                            if listNews!.count == 0{
                                self.pageRefreshes[catPage].normalTitle = "没有更多了"
                            }else{
                                self.pageRefreshes[catPage].normalTitle = "加载更多"
                            }
                        }
                        
                    }
                    
                }catch let ex{
                    
                    print(ex)
                }
            }).resume()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView.tag {
        case tabbarTableView.tag:
            if tabItems != nil {
                return tabItems!.count
            }
            return 0
        default:
            if tableView.tag / 100 == 7 {
                let tabTag = tableView.tag - 700
                if catDatas[tabTag].count > 0{
                    return catDatas[tabTag].count
                }else{
                    return 1
                }
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch tableView.tag {
        case tabbarTableView.tag:
//            if tabItems != nil {
//                let catInfo = tabItems?.object(at: indexPath.row) as? NSDictionary
//                
//                let catName = catInfo?.object(forKey: "name") as? String
//                
//                if catName != nil{
//                    return (catName! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
//                }
//                
//            }
            return catWidth
        default:
            if tableView.tag / 100 == 7 {
                return 88
            }
            return 44
        }
    }
    
    /*
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if tableView.tag / 100 == 7 {
            let tabTag = tableView.tag - 700
            if catDatas[tabTag].count > 0{
                let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 64))
                footer.backgroundColor = UIColor.white
                footer.addSubview(pageRefreshes[tabTag])
                return footer
            }
        }
        return nil
    }
    */
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        switch tableView.tag {
        case tabbarTableView.tag:
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            if tabItems != nil {
                let catInfo = tabItems?.object(at: indexPath.row) as? NSDictionary
                
                let titleStr = catInfo?.object(forKey: "name") as? String
//                var titleWidth:CGFloat = 0.0
//                if titleStr != nil{
//                    titleWidth = (titleStr! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 36), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14)], context: nil).width + 32
//                }
                let titleWidth = catWidth
                
                let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: titleWidth, height: 36))
                titleLabel.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI/2))
                titleLabel.center = CGPoint(x: 18, y: titleWidth/2)
                titleLabel.textAlignment = .center
                titleLabel.textColor = UIColor.white
                cell.addSubview(titleLabel)
                
                titleLabel.font = UIFont.systemFont(ofSize: 14)
                titleLabel.text = titleStr
                
                if indexPath.row == seletedTabIndex {
                    let seletedBar = UIView(frame: CGRect(x: 0, y: 0, width: 2, height: titleWidth))
                    seletedBar.backgroundColor = themeColor1
                    cell.addSubview(seletedBar)
                }
            }
            break
        default:
            if tableView.tag / 100 == 7 {
                let tabTag = tableView.tag - 700
                if catDatas[tabTag].count > 0{
//                    cell.textLabel?.text = "\(indexPath.row)"
                    
                    let thumbView = UIImageView(frame: CGRect(x: 16, y: 8, width: 96, height: 72))
                    thumbView.backgroundColor = UIColor.lightGray
                    thumbView.contentMode = .scaleAspectFill
                    thumbView.layer.masksToBounds = true
                    cell.addSubview(thumbView)
                    
                    let titleLabel = UILabel(frame: CGRect(x: 120, y: 8, width: view.frame.width - 120 - 16, height: 28))
                    titleLabel.font = UIFont.systemFont(ofSize: 18)
                    cell.addSubview(titleLabel)
                    
                    let desLabel = UILabel(frame: CGRect(x: 120, y: 44, width: view.frame.width - 120 - 16, height: 36))
                    desLabel.numberOfLines = 2
                    desLabel.font = UIFont.systemFont(ofSize: 14)
                    desLabel.textColor = UIColor.lightGray
                    cell.addSubview(desLabel)
                    
                    let articleInfo = catDatas[tabTag].object(at: indexPath.row) as? NSDictionary
                    
                    titleLabel.text = articleInfo?.object(forKey: "title") as? String
                    desLabel.text = articleInfo?.object(forKey: "description") as? String
                    
                    let thumbUrlStr = articleInfo?.object(forKey: "thumb") as? String
                    if thumbUrlStr != nil{
                        let thumbURL = URL(string: "\(baseDomainName)/\(thumbUrlStr!)")
                        if thumbURL != nil{
                            URLSession.shared.dataTask(with: thumbURL!, completionHandler: { (data:Data?, resp:URLResponse?, err: Error?) in
                                if err == nil{
                                    if data != nil{
                                        DispatchQueue.main.async {
                                            thumbView.image = UIImage(data: data!)
                                        }
                                    }
                                }
                            }).resume()
                        }
                    }
                    
                }else{
                    let emptyView = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width-32, height: 28))
                    emptyView.font = UIFont.systemFont(ofSize: 14)
                    emptyView.textColor = UIColor.lightGray
                    emptyView.text = "暂未找到相关文章"
                    emptyView.textAlignment = .center
                    cell.addSubview(emptyView)
                }
            }
            break
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch tableView.tag {
        case tabbarTableView.tag:
            seletedTabIndex = indexPath.row
            tabScrollView.setContentOffset(CGPoint(x: tabScrollView.frame.width * CGFloat(_currentTab), y: 0), animated: true)
            if catDatas[seletedTabIndex].count == 0{
                refreshList(seletedTabIndex)
            }
            break
        default:
            if tableView.tag / 100 == 7 {
                tableView.deselectRow(at: indexPath, animated: true)
                let tabTag = tableView.tag - 700
                if catDatas[tabTag].count > 0{
                    let info = catDatas[tabTag].object(at: indexPath.row) as? NSDictionary
                    
                    let weburlstr = info?.object(forKey: "url") as? String
                    let title = info?.object(forKey: "title") as? String
                    let aid = info?.object(forKey: "news_id") as? String
                    
                    var fromMy = true
                    if weburlstr != nil{
                        let weburl = URL(string: weburlstr!)
                        if weburl != nil{
                            fromMy = false
                            hidesBottomBarWhenPushed = true
                            navigationController?.pushViewController(WebArticleViewController(title: title ?? "文章", url: weburl!, id: aid), animated: true)
                        }
                        
                    }
                    
                    if fromMy{
                        
                        if aid != nil{
                            hidesBottomBarWhenPushed = true
                            navigationController?.pushViewController(FCArticleViewController(title: title ?? "文章", id: aid!), animated: true)
                        }
                    }
                    
                }
            }
            break
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
